package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;


/**
 * 设备管理Service业务层处理
 *
 * @author alexis
 * @date 2025-11-11
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto deviceDto) {
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice updateDevice = new UpdateDevice();
        updateDevice.setDeviceName(deviceDto.getDeviceName());
        request.withBody(updateDevice);
        client.updateDevice(request);

        Device device = new Device();
        BeanUtils.copyProperties(deviceDto, device);
        return updateById(device)?1:0;
    }

    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProducts() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));

    }

    @Override
    public List<ProductVo> allProduct() {
        String result = redisTemplate.opsForValue().get(CacheConstants.ALL_PRODUCT_LIST);
        if (StringUtils.isEmpty(result)) {
            return new ArrayList<ProductVo>();
        }
        List<ProductVo> list = JSONUtil.toList(result, ProductVo.class);
        return list;
    }

    @Override
    public void register(DeviceDto deviceDto) {
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getNodeId, deviceDto.getNodeId())
                .or().eq(Device::getDeviceName, deviceDto.getDeviceName());
        long count = count(wrapper);
        if (count > 0) {
            throw new BaseException("设备名称或者设备标识码已经存在");
        }

        LambdaQueryWrapper<Device> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation());
        long count2 = count(wrapper2);
        if (count2 > 0) {
            throw new BaseException("设备已经注册");
        }

        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setProductId(deviceDto.getProductKey());
        addDevice.setDeviceName(deviceDto.getDeviceName());
        addDevice.setNodeId(deviceDto.getNodeId());
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replace("-", "");
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        request.withBody(addDevice);
        AddDeviceResponse response = client.addDevice(request);

        Device device = new Device();
        BeanUtils.copyProperties(deviceDto, device);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);

        save(device);
    }

    @Override
    public DeviceDetailVo getDeviceDetail(String iotId) {
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId, iotId);
        Device device = deviceMapper.selectOne(wrapper);
        if (device == null) {
            throw new BaseException("设备不存在");
        }

        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);

        DeviceDetailVo deviceDetailVo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, deviceDetailVo);
        deviceDetailVo.setDeviceStatus(response.getStatus());

        String activeTimeStr = response.getActiveTime();

        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;
    }

    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        List<Map<String, Object>> result = new ArrayList<>();

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);

        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty( shadow)) {
            return result;
        }

        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        String activeTime = shadow.get(0).getReported().getEventTime();
        LocalDateTime eventTime = LocalDateTimeUtil.parse(activeTime, "yyyyMMdd'T'HHmmss'Z'");
        final LocalDateTime eventTime2 = eventTime.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();


        jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime2);
            result.add(map);
        });


        return result;
    }

    @Override
    @Transactional
    public void deleteDeviceByIotId(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        client.deleteDevice(request);

        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId, iotId);
        remove(wrapper);
    }

    @Override
    public AjaxResult queryProduct(String productKey) {
        if(StringUtils.isEmpty(productKey)){
            throw new BaseException("请输入正确的产品Key");
        }
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        return AjaxResult.success(serviceCapabilities);
    }
}
